package cn.itcast.Servlet;

import cn.itcast.domain.Cake;
import cn.itcast.domain.CakeDB;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/purchase")
public class Purchase extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        request.removeAttribute("id");
        Cake ncake= CakeDB.getCake(id);
        HttpSession session = request.getSession();
        List<Cake> cart= (List) session.getAttribute("cart");
        //如果购物车为空
        if (cart==null){
            //创建一个新的购物车并加到session域里
            cart=new ArrayList<Cake>();
            session.setAttribute("cart",cart);
        }
        cart.add(ncake);
        int totalprice= 0;
        if (session.getAttribute("totalprice")!=null)
            totalprice= (int) session.getAttribute("totalprice");
        totalprice+=ncake.getPrice();
        session.setAttribute("totalprice",totalprice);
        response.sendRedirect(request.getContextPath()+"/carts.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
